package com.ryan.pintu.view;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;
import org.anddev.andengine.entity.scene.background.SpriteBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.content.Context;
import android.content.Intent;
import android.util.DisplayMetrics;

import com.gfan.sdk.statitistics.GFAgent;
import com.ryan.pintu.Level;
import com.ryan.pintu.MenuSprite;
import com.ryan.pintu.UriBitmapTextureAtlasSource;

public class Menu extends BaseGameActivity{
    private static int CAMERA_WIDTH ;
    private static int CAMERA_HEIGHT ;
    
    private static int TOP= 70;
    private static int BOTTOM= 110;
    private static int SPACING_X;
    private static int SPACING_Y;
    
    
    private Level mGameLevel;
    private Camera mCamera;
    private BitmapTextureAtlas mBitmapTexture;
    private BitmapTextureAtlas mBgTexture;
    private TextureRegion mLockTextureRegion;
    private TextureRegion mBgRegion;
    private TextureRegion[] mPicTextureRegion;
    private Sprite[] mPicSprite;
    private int mStage;
    
    @Override
    protected void onResume() {
        super.onResume();
        GFAgent.onResume (this);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        GFAgent.onPause(this);
    }
    
    @Override
    public Engine onLoadEngine() {
        mStage = getIntent().getIntExtra("stage", 0);
        
        //load display metrics
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        CAMERA_WIDTH = dm.widthPixels;
        CAMERA_HEIGHT = dm.heightPixels;
        
        int width = CAMERA_WIDTH;
        int height = CAMERA_HEIGHT-TOP-BOTTOM;
        SPACING_X = (width-Level.WID*Level.LEN_X)/(Level.LEN_X+1);
        SPACING_Y = (height-Level.HEI*Level.LEN_Y)/(Level.LEN_Y-1);
        
        
        mGameLevel = Main.getGameLevel(this);
        
        this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
        return new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT,
                new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
    }

    @Override
    public void onLoadResources() {
        BitmapTextureAtlasTextureRegionFactory.setCreateTextureRegionBuffersManaged(true);
        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("img/");
        FontFactory.setAssetBasePath("font/");

        int textureSize = mGameLevel.loadTextureSize();
        this.mBitmapTexture = new BitmapTextureAtlas(textureSize, textureSize, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        this.mBgTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        
        int atlas_x=0,atlas_y=0,next_atlas_y=0;
        this.mLockTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTexture, this, "lock.jpg",0,0);
        this.mBgRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBgTexture, this, "bg.jpg",0,0);

        atlas_x = 60;atlas_y=0;next_atlas_y=80;
        
        int size = Level.MAX_CLAZ_NUM;
        this.mPicTextureRegion = new TextureRegion[size];
        for(int i=0;i<size ;i++){
            IBitmapTextureAtlasSource source = new UriBitmapTextureAtlasSource(Menu.this,"assets_img/"+mStage+"/"+i+".jpg",
                    Level.WID,Level.HEI);
            
            int posX,posY;
            if( (atlas_x+source.getWidth())>textureSize ){
                posX=0;
                posY=next_atlas_y;
                atlas_x= source.getWidth();
                atlas_y = next_atlas_y;
                next_atlas_y = next_atlas_y+source.getHeight();
            }else{
                posX=atlas_x;
                posY=atlas_y;
                atlas_x= atlas_x+source.getWidth();
                //atlas_y = atlas_y;
                next_atlas_y = Math.max(next_atlas_y, source.getHeight());
            }
            this.mPicTextureRegion[i] =BitmapTextureAtlasTextureRegionFactory.createFromSource(mBitmapTexture, 
                    source, posX, posY);
                
        }
        
        this.mEngine.getTextureManager().loadTextures(this.mBitmapTexture,mBgTexture);
    }
    
    @Override
    public void onResumeGame() {
    	super.onResumeGame();
    
    	final int level = Main.getStageLevel(this,mStage);
    	if(level<0){
    	    return ; 
    	}
    	final Scene sc = getEngine().getScene();
    	sc.detachChildren();
    	sc.clearTouchAreas();
    	
    	
    	for(int i=0;i<Level.LEN_Y;i++){
            for(int j=0;j<Level.LEN_X;j++){
                int now = i*Level.LEN_X+j;
                TextureRegion tr;
                if(now<=level){
                    tr = Menu.this.mPicTextureRegion[now];
                }else{
                    tr = Menu.this.mLockTextureRegion;
                }
                mPicSprite[now]=new MenuSprite(new Level(mStage, now),SPACING_X+j*(SPACING_X+Level.WID), 
                        TOP+i*(SPACING_Y+Level.HEI),Level.WID,Level.HEI, tr.deepCopy());
                sc.attachChild(mPicSprite[now]);
                if(now<=level){
                    sc.registerTouchArea(mPicSprite[now]);
                }
            }
        }
    	
    }

    @Override
    public Scene onLoadScene() {
        this.mEngine.registerUpdateHandler(new FPSLogger());
        final Scene scene = new Scene();
        scene.setBackground(new SpriteBackground(new Sprite(0, 0,CAMERA_WIDTH,CAMERA_HEIGHT,mBgRegion)));
        
        this.mPicSprite = new Sprite[this.mGameLevel.getStageSize()];
        
        scene.setOnAreaTouchListener(new Scene.IOnAreaTouchListener() {
            ITouchArea touchingArea = null;
            
            
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent, ITouchArea pTouchArea,
                    float pTouchAreaLocalX, float pTouchAreaLocalY) {
                if(pSceneTouchEvent.isActionDown()){
                    touchingArea = pTouchArea;
                }else if (pSceneTouchEvent.isActionUp()){
                    if(touchingArea == pTouchArea){
                        MenuSprite menuSprite = (MenuSprite)pTouchArea;
                        Menu.startLv(Menu.this, menuSprite.getLv());
                    }
                    touchingArea = null;
                }
                
                return true;
            }
        });
        
        return scene;
    }

    @Override
    public void onLoadComplete() {
        
    }
    
    public static void startLv(Context ctx,Level lv){
        Intent intent = new Intent(ctx,Game.class);
        intent.putExtra("level", lv);
        ctx.startActivity(intent);
    }

}
